import { Input, NavBar } from 'antd-mobile'
import classnames from 'classnames'
import { useHistory } from 'react-router-dom'
import { Icon } from '@/components/Icon'
import styles from './index.module.scss'
import { io, Socket } from 'socket.io-client'
import { useEffect, useRef, useState } from 'react'
import { getToken } from '@/utils/token'

const Chat = () => {
  const history = useHistory()

  //
  type Chat = {
    type: 'xz' | 'user'
    message: string
  }

  const [chatList, setChatList] = useState<Chat[]>([])
  const [value, setValue] = useState('')
  // 创建ref变量,来存储socketio实例,来实现多个方法中共享
  const socketRef = useRef<Socket>()

  // 一进入页面就开始获取连接
  useEffect(() => {
    // 1.建立socket连接
    const socketio = io('http://toutiao.itheima.net', {
      // 2.设置参数
      query: {
        token: getToken().token,
      },
      // 3.连接方式
      transports: ['websocket'],
    })

    // 默认值
    socketio.on('connect', () => {
      setChatList([
        {
          type: 'xz',
          message: '你好！我是小智',
        },
      ])
    })

    // 接收成功返回的
    socketio.on('message', (data) => {
      setChatList((chatList) => [
        ...chatList,
        {
          type: 'xz',
          message: data.msg,
        },
      ])
    })

    // 将socket实例保存在
    socketRef.current = socketio
    // 离开页面关闭连接
    return () => {
      socketio.close()
    }
  }, [])

  // 回车发送信息
  const onKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.code === 'Enter') {
      console.log('敲击了回车', e)

      setChatList([
        ...chatList,
        {
          type: 'user',
          message: value,
        },
      ])

      // 将信息发送给socket服务器
      socketRef.current?.emit('message', {
        msg: value,
        timestamp: Date.now() + '',
      })
      setValue('')
    }
  }

  return (
    <div className={styles.root}>
      <NavBar className="fixed-header" onBack={() => history.go(-1)}>
        小智同学
      </NavBar>

      <div className="chat-list">
        {chatList.map((item, index) => (
          <div
            key={index}
            className={classnames(
              'chat-item',
              item.type === 'xz' ? 'self' : 'user'
            )}
          >
            {item.type === 'xz' ? (
              <Icon type="iconbtn_xiaozhitongxue" />
            ) : (
              <img src="http://geek.itheima.net/images/user_head.jpg" alt="" />
            )}
            <div className="message">{item.message}</div>
          </div>
        ))}
      </div>

      <div className="input-footer">
        <Input
          className="no-border"
          value={value}
          onChange={(val) => setValue(val)}
          onKeyDown={(e) => onKeyDown(e)}
          placeholder="请描述您的问题"
        />
        <Icon type="iconbianji" />
      </div>
    </div>
  )
}

export default Chat
